using System;
using System.Collections.Generic;
using System.Text;

namespace Avanzis.Helpers.PersistentObjects
{
    /// <summary>
    /// Class to allow scopes to reach the implementation
    /// of <see cref="IThreadScopeInfo"/>. Also implements 
    /// the <see cref="IThreadScopeInfo"/> delegating the calls to 
    /// the scope set.
    /// </summary>
    public sealed class ThreadScopeAccessor : IThreadScopeInfo
    {
        private static readonly ThreadScopeAccessor instance = new ThreadScopeAccessor();

        private IThreadScopeInfo scopeInfo;

        public static ThreadScopeAccessor Instance
        {
            get { return instance; }
        }

        public IThreadScopeInfo ScopeInfo
        {
            get { return scopeInfo; }
            set { scopeInfo = value; }
        }

        #region IThreadScopeInfo Members

        public Stack<ISessionScope> CurrentStack
        {
            get { return scopeInfo.CurrentStack; }
        }

        public ISessionScope GetRegisteredScope()
        {
            if (scopeInfo == null)
            {
                throw new PersistentObjectsException(
                    "Can't get registered scope because the Active Record framework was not initialized.");
            }
            return scopeInfo.GetRegisteredScope();
        }

        public void RegisterScope(ISessionScope scope)
        {
            if (scopeInfo == null)
            {
                throw new PersistentObjectsException("A scope tried to registered itself within the framework, " +
                                                "but the Active Record was not initialized");
            }
            scopeInfo.RegisterScope(scope);
        }

        public void UnRegisterScope(ISessionScope scope)
        {
            scopeInfo.UnRegisterScope(scope);
        }

        public bool HasInitializedScope
        {
            get { return scopeInfo.HasInitializedScope; }
        }

        #endregion
    }
}
